# -*- coding: utf-8 -*-
import sys
import logging
from lxml import etree
from xrisks.model import *
from xrisks.lib.base import *

log = logging.getLogger(__name__)

class IndicatorsController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py file has
    # a resource setup:
    #     map.resource('indicator', 'indicators')


    def index(self, format='html'):
        """GET /indicators: All items in the collection."""
        # url_for('indicators')
        pass

    def getByRisk(self, risk):
        risk = Session.query(Risk).get(risk)
        if risk is not None:
            c.risk = risk
            response.headers['content-type'] = 'text/xml; charset=utf-8'
            return render('/indicators/list.mako')
        else:
            abort(404)

    def create(self):
        """POST /indicators: Create a new item."""
        # url_for('indicators')
        pass

    def createByRisk(self, risk):
        """POST /impacts: Create a new item."""
        # url_for('create_impacts_by_risk')
        try:
            risk = Session.query(Risk).get(risk)
            if risk is not None:
                content = request.body.read(int(request.environ['CONTENT_LENGTH']))
                if not content:
                    content = request.params.get('xml')
                doc = etree.fromstring(content.encode("utf8"))
                name = doc.xpath('/indicator/name')[0].text
                description = doc.xpath('/indicator/description')[0].text
                #Guardamos el impacto
                indicator = Indicator(name, description)
                risk.indicators.append(indicator)
                Session.save(indicator)
                Session.commit()
                del response.headers['Content-Type']
                response.headers['Location'] = h.url_for('risk', id=risk.id)
                response.status_code = 201
                return
            else:
                abort(404)
        except:
            print "ERROR: ", sys.exc_info()[0]
            abort(400)

    def new(self, format='html'):
        """GET /indicators/new: Form to create a new item."""
        # url_for('new_indicator')
        pass

    def update(self, id):
        """PUT /indicators/id: Update an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(h.url_for('indicator', id=ID),
        #           method='put')
        # url_for('indicator', id=ID)
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            doc = etree.fromstring(content)
            indicator = Session.query(Indicator).get(id)
            name = None
            if indicator is not None:
                name = doc.xpath('/indicator/name')
                if name:
                    indicator.name = name[0].text
                description = doc.xpath('/indicator/description')
                if description:
                    indicator.description = description[0].text
                #Session.save(indicator)
                Session.commit()
                response.headers['Content-Type'] = 'text/xml; charset=utf-8'
                return
            else:
                abort(404)
        except:
            abort(400)

    def delete(self, id):
        """DELETE /indicators/id: Delete an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(h.url_for('indicator', id=ID),
        #           method='delete')
        # url_for('indicator', id=ID)
        indicator = Session.query(Indicator).get(id)
        if indicator:
            Session.delete(indicator)
            Session.commit()
        del response.headers['Content-Type']
        response.status_code = 204
        return

    def show(self, id, format='html'):
        """GET /indicators/id: Show a specific item."""
        # url_for('indicator', id=ID)
        pass

    def edit(self, id, format='html'):
        """GET /indicators/id;edit: Form to edit an existing item."""
        # url_for('edit_indicator', id=ID)
        pass
